﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;

namespace _007_TCPClient_BF
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0) // clent
            {
                IPEndPoint end_point = new IPEndPoint(IPAddress.Loopback, 6666);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(end_point);

                MyObject object2send = new MyObject(1, "Hello world!");
                BinaryFormatter bf = new BinaryFormatter();
                NetworkStream ns = new NetworkStream(socket);
                bf.Serialize(ns, object2send);
                ns.Flush();
                socket.Shutdown(SocketShutdown.Send);
                socket.Disconnect(false);
            }
            else
            {
                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6666);
                Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

                server.Bind(ipep);
                server.Listen(20);
                Socket socket = server.Accept();
                BinaryFormatter bf = new BinaryFormatter();
                NetworkStream ns = new NetworkStream(socket);
                MyObject object2receive = (MyObject)bf.Deserialize(ns);
                Console.WriteLine("Server receive: {0},{1}", object2receive.Id, object2receive.Name);
                socket.Shutdown(SocketShutdown.Both);
                socket.Disconnect(false);
                //server.Shutdown(SocketShutdown.Both);
            }

        }
    }
}
